package cn.itcast.order.configuration;

/**
 * @author danDong
 * @date 2025-05-06 10:47:20
 */
public class VolatileExample {
    // 没有使用volatile修饰的共享变量
    private volatile boolean flag = true;

    public void startThreads() {
        // 启动两个线程来检查flag的值
        new Thread(() -> {
            while (flag) {
                // 不断地输出线程名称和flag的值
                System.out.println(Thread.currentThread().getName() + " sees flag as true");
            }
            System.out.println(Thread.currentThread().getName() + " exits because flag is false");
        }, "Thread-1").start();

        new Thread(() -> {
            while (flag) {
                // 不断地输出线程名称和flag的值
                System.out.println(Thread.currentThread().getName() + " sees flag as true");
            }
            System.out.println(Thread.currentThread().getName() + " exits because flag is false");
        }, "Thread-2").start();

        new Thread(() -> {
            while (flag) {
                // 不断地输出线程名称和flag的值
                System.out.println(Thread.currentThread().getName() + " sees flag as true");
            }
            System.out.println(Thread.currentThread().getName() + " exits because flag is false");
        }, "Thread-3").start();

        new Thread(() -> {
            while (flag) {
                // 不断地输出线程名称和flag的值
                System.out.println(Thread.currentThread().getName() + " sees flag as true");
            }
            System.out.println(Thread.currentThread().getName() + " exits because flag is false");
        }, "Thread-4").start();

        new Thread(() -> {
            while (flag) {
                // 不断地输出线程名称和flag的值
                System.out.println(Thread.currentThread().getName() + " sees flag as true");
            }
            System.out.println(Thread.currentThread().getName() + " exits because flag is false");
        }, "Thread-5").start();
    }

    public void changeFlag() {
        // 修改flag的值
        flag = false;
        System.out.println("Main thread changed flag to false");
    }

    public static void main(String[] args) {
        VolatileExample example = new VolatileExample();

        example.startThreads();

        // 等待一段时间，然后修改flag的值
        try {
            Thread.sleep(1000); // 1秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        example.changeFlag();
    }
}